<template>
<div class="ivu-card ivu-card-bordered ivu-card-dis-hover">
  <div class="ivu-card-head"><p>{{ $route.meta.title }}</p></div>
  <div class="ivu-card-body">
    <iForm ref="formRef" :model="formModel" :rules="formRules" :label-width="100">

      <FormItem prop="title" label="标题：">
        <Input v-model="formModel.title" placeholder="名称"/>
      </FormItem>

      <FormItem label="图片(建议高度:160px)：">
        <Upload ref="uploadRef" :action="config.uploadAction" accept="image/*" :format="['jpg','jpeg','png']" :maxSize="2048" :on-success="onUploadSuccess" :on-remove="onUploadRemove">
          <Button v-if="!formModel.image" type="ghost" icon="ios-cloud-upload-outline">上传</Button>
        </Upload>
      </FormItem>

      <FormItem>
        <Button type="primary" :loading="submitLoading" @click="onClickSubmit">创建</Button>
        <Button type="ghost" @click="$router.go(-1);">返回</Button>
      </FormItem>
    </iForm>
  </div>
</div>
</template>

<script>
import qs from 'qs';
import { Form, Input, Button, Upload, Message } from 'iview';
import auth from '@/utils/auth';
import config from '@/config';
import ajaxiView from '@/utils/ajaxiView';

export default {
  components: {
    [Form.name]: Form,
    [Form.Item.name]: Form.Item,
    [Input.name]: Input,
    [Button.name]: Button,
    [Upload.name]: Upload
  },
  data() {
    return {
      config,
      token: auth.getToken(),
      formModel: {
        title: '',
        image: '',
        status: '0'
      },
      submitLoading: false,
      formRules: {
        title: [
          {type:'string', required: true, message: '请输入标题!', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    onUploadSuccess(response, file, fileList) {
      if(response.code != 0) {
        Message.error(response.msg);
      }
      Message.success(response.msg);

      this.formModel.image = response.files[0];
    },
    onUploadRemove(file, fileList) {
      this.formModel.image = '';
    },
    onClickSubmit() {
      var _this = this;
      if(!this.formModel.image) {
        Message.error('图片不存在,请上传');
        return false;
      }

      _this.$refs.formRef.validate((valid) => {
        _this.submitLoading = true;

        if(valid) {
          ajaxiView.post('/backstage/swipe?token='+_this.token, qs.stringify(_this.formModel)).then(function(data) {
            if(data !== false) {
              Message.success({
                content: data.msg,
                onClose: function() {
                  _this.$router.push({ name: 'systemSwipeIndex' });
                }
              });
            }

            _this.submitLoading = false;
          });
        } else {
          _this.submitLoading = false;
        }
      });
    }
  }
}
</script>

<style>
</style>